package com.qianwei.footpath.ui;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

import com.common.baselib.string.GsonUtil;
import com.qianwei.footpath.R;
import com.qianwei.footpath.base.BaseActivity;
import com.qianwei.footpath.bean.BodyCompositionData;
import com.qianwei.footpath.bean.LoginUserBean;
import com.qianwei.footpath.iview.IResultView;
import com.qianwei.footpath.manage.BalanceAnalyzer;
import com.qianwei.footpath.manage.DataManager;
import com.qianwei.footpath.manage.LocalCacheDataManage;
import com.qianwei.footpath.manage.TimerManager;
import com.qianwei.footpath.param.WeChatUpdateParam;
import com.qianwei.footpath.presenter.ResultPresenter;
import com.qianwei.footpath.utils.TextToSpeechUtils;

import java.util.List;
import java.util.TimerTask;

public class TestResult extends BaseActivity<ResultPresenter> implements IResultView {
    private static final String TAG = "Test---";
    private TextView tvDown, tvBalanceForceResult, tvHeight, tvWeight, tvBmi;
    private TimerTask testTimeTask;
    private int testDownLoadTime = 30;
    private TextToSpeechUtils ttsUtils;

    private double heightResultValue, weightResultValue, bmiResultValue;
    private String bmiCategory;
    private int heartRateResultValue;
    private BodyCompositionData bodyCompositionData;
    private List<Double> weights;
    private String balanceForceResult;
    private String imei = "02ad3fa2972eb9417c982289abd405ba";
    private boolean isGetLoginUser = false;

    @Override
    protected int layoutId() {
        return R.layout.result_activity;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        tvDown = findViewById(R.id.tvDown);
        tvBalanceForceResult = findViewById(R.id.tvBalanceForceResult);
        tvHeight = findViewById(R.id.tvHeight);
        tvWeight = findViewById(R.id.tvWeight);
        tvBmi = findViewById(R.id.tvBmi);


        testDownLoadTime = LocalCacheDataManage.getLocalConfigData().getPhysical_test_timeout();

        heartRateResultValue = DataManager.getInstance().getHeartRateResultValue();
        heightResultValue = DataManager.getInstance().getHeightResultValue();
        weightResultValue = DataManager.getInstance().getWeightResultValue();
        bmiResultValue = DataManager.getInstance().getBmiResultValue();
        bmiCategory = DataManager.getInstance().getBmiCategory();
        bodyCompositionData = DataManager.getInstance().getBodyCompositionData();
        weights = DataManager.getInstance().getWeights();

        Log.e(TAG, "weights: " + GsonUtil.getGson().toJson(weights));
        Log.e(TAG, "bodyCompositionData: " + GsonUtil.getGson().toJson(bodyCompositionData));
        Log.e(TAG, "bmiCategory: " + bmiCategory);
        Log.e(TAG, "heartRateResultValue: " + heartRateResultValue);
        Log.e(TAG, "heightResultValue: " + heightResultValue);
        Log.e(TAG, "weightResultValue: " + weightResultValue);
        Log.e(TAG, "bmiResultValue: " + bmiResultValue);

        tvDown.setOnClickListener(v -> finish());


        tvHeight.setText(String.format("%.1f", heightResultValue));
        tvWeight.setText(String.format("%.1f", weightResultValue));
        tvBmi.setText(String.format("%.1f", bmiResultValue));

        BalanceAnalyzer.BalanceResult result = BalanceAnalyzer.analyzeBalance(weights);
        switch (result) {
            case EXCELLENT:
                balanceForceResult = "优秀";
                break;
            case GOOD:
                balanceForceResult = "良好";
                break;
            case POOR:
                balanceForceResult = "较差";
                break;
            case INVALID_DATA:
                balanceForceResult = "?";
                break;
            default:
                balanceForceResult = "";
        }
        tvBalanceForceResult.setText(balanceForceResult);


        initTTS();

        startTimeTask();
    }

    private void getLoginUser() {
        isGetLoginUser = true;
        presenter.getLoginUser(DataManager.getInstance().getImei());
    }

    private void initTTS() {
        ttsUtils = new TextToSpeechUtils(this, new TextToSpeechUtils.OnInitListener() {
            @Override
            public void onInitSuccess() {
                new Handler().postDelayed(() -> speak("测试结束，您的平衡力测试结果为" + balanceForceResult
                        + ",身高为" + String.format("%.1f", heightResultValue)
                        + "厘米，体重为" + String.format("%.1f", weightResultValue)
                        + "千克，BMI为" + String.format("%.1f", bmiResultValue), "success", new TextToSpeechUtils.OnPlayListener() {
                    @Override
                    public void onStart(String utteranceId) {

                    }

                    @Override
                    public void onDone(String utteranceId) {
                        if ("success".equals(utteranceId)) {
                            runOnUiThread(() -> {
                                stopTimeTask(testTimeTask);
                                testTimeTask = null;
                                startTimeTask();
                            });
                        }
                    }

                    @Override
                    public void onError(String utteranceId, int errorCode) {
                        if ("success".equals(utteranceId)) {
                            runOnUiThread(() -> {
                                stopTimeTask(testTimeTask);
                                testTimeTask = null;
                                startTimeTask();
                            });

                        }
                    }
                }), 100);
            }

            @Override
            public void onInitFailed(int errorCode) {

            }
        });

    }

    private void speak(String text, String utteranceId, TextToSpeechUtils.OnPlayListener listener) {
        ttsUtils.speak(text, utteranceId, listener);
    }

    private void startTimeTask() {
        if (testTimeTask == null) {
            testTimeTask = new TimerTask() {
                private int secondsPassed = 0;

                @Override
                public void run() {
                    secondsPassed++;
                    runOnUiThread(() -> {
                        int dif = testDownLoadTime - secondsPassed;
                        tvDown.setText("返回(" + dif + "s)");
                        if (!isGetLoginUser) {
                            getLoginUser();
                        }
                    });
                    if (secondsPassed >= testDownLoadTime) {
                        finish();
                    }
                }
            };
            TimerManager.getInstance().startTimer(1000, 1000, testTimeTask);
        }
    }


    private void stopTimeTask(TimerTask timerTask) {
        if (timerTask != null) {
            TimerManager.getInstance().stopTimer(timerTask);
            timerTask.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        stopTimeTask(testTimeTask);
        if (ttsUtils != null) {
            ttsUtils.release();
            ttsUtils = null;
        }
        super.onDestroy();
    }

    @Override
    protected ResultPresenter createPresenter() {
        return new ResultPresenter();
    }

    @Override
    public void getLoginUser(LoginUserBean bean) {
        if (bean != null) {
            if (bodyCompositionData == null) return;
            WeChatUpdateParam param = new WeChatUpdateParam(bean.getId(), String.valueOf(heightResultValue), String.valueOf(weightResultValue),
                    String.valueOf(heartRateResultValue), String.valueOf(bmiResultValue), String.valueOf(bodyCompositionData.getBodyFatRate()),
                    String.valueOf(bodyCompositionData.getBodyWaterRate()), String.valueOf(bodyCompositionData.getProtein()), String.valueOf(bodyCompositionData.getIntracellularFluid()), String.valueOf(bodyCompositionData.getExtracellularFluid()),
                    String.valueOf(bodyCompositionData.getMuscleMass()), String.valueOf(bodyCompositionData.getBasalMetabolism()), String.valueOf(bodyCompositionData.getFatFreeWeight()), String.valueOf(bodyCompositionData.getInorganicSalt()));
            Log.e(TAG, "上传的参数: " + GsonUtil.getGson().toJson(param));
            presenter.getWeChatUpdate(param);
        } else {
            isGetLoginUser = false;
        }
    }
}
